import { Row, Col, Form, Checkbox, Radio, Button, message, Icon } from 'antd';
import _ from 'lodash';
import moment from 'moment';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const ButtonGroup = Button.Group;

const formLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 }
};
const buttonLayout = {
  span: '16',
  offset: '8'
};

let UnitDeployForm = ({ form, machines, builds, listBuilds, startUnit, restartUnit, stopUnit }) => {
  const { getFieldProps, getFieldsValue } = form;

  const imageField = getFieldProps('image', {
    initialValue: _.isEmpty(builds) ? undefined : builds[0].image
  });

  const getFormValues = () => {
    const formValues = getFieldsValue();
    const machineIds = _.compact(_.map(formValues, (v, key) => {
      if (key.startsWith('machineId-') && v === true) {
        return parseInt(key.split('-')[1], 10);
      }
      return undefined;
    }));
    return { image: formValues.image, machineIds };
  };

  const onRestart = () => {
    const values = getFormValues();
    if (_.isEmpty(values.machineIds)) {
      message.info('请选中至少一台机器');
      return;
    }
    restartUnit(values.image, values.machineIds);
  };
  const onDeploy = () => {
    const values = getFormValues();
    if (_.isEmpty(values.machineIds)) {
      message.info('请选中至少一台机器');
      return;
    }
    startUnit(values.image, values.machineIds);
  };

  const onStop = () => {
    const values = getFormValues();
    if (_.isEmpty(values.machineIds)) {
      message.info('请选中至少一台机器');
      return;
    }
    stopUnit(values.image, values.machineIds);
  };

  const isMachineSelected = !_.isEmpty(getFormValues().machineIds);

  return (
    <Form horizontal form={form} className='unit-deploy-form'>
      <FormItem required label='选择机器：' {...formLayout}>
        {_.isEmpty(machines)
          ? '暂无可用机器，请先在设置中分配机器'
          : machines.map(({ id, ip }) => {
            return (
              <label key={id} className='ant-checkbox-vertical'>
                <Checkbox {...getFieldProps(`machineId-${id}`)}/>{ip}
              </label>
            );
          }
        )
        }
      </FormItem>
      <FormItem label='选择 Image：' {...formLayout}>
        {_.isEmpty(builds)
          ? '暂无成功 Build 的 Image'
          : (
          <RadioGroup {...imageField}>
            {builds.map(({ id, image, updatedAt }) => {
              return (
                <Radio key={id} value={image}>
                  {`${image} build at ${moment(updatedAt)
                    .format('YYYY-MM-DD HH:mm:ss')}`}
                </Radio>
              );
            })}
          </RadioGroup>
        )
        }
        <br/>
        <a onClick={listBuilds}><Icon type='reload'/> 刷新</a>
      </FormItem>
      <Row>
        <Col {...buttonLayout}>
          <ButtonGroup>
            <Button type='primary' disabled={_.isEmpty(builds) || !isMachineSelected} onClick={onDeploy}>
              <Icon type='caret-right'/>部署
            </Button>
            {/* TODO 这里不应该和 onDeploy 一样 */}
            <Button disabled={!isMachineSelected} onClick={onRestart}><Icon type='reload'/>重启</Button>
            <Button disabled={!isMachineSelected} type='ghost' onClick={onStop}><Icon type='pause'/>停止</Button>
          </ButtonGroup>
        </Col>
      </Row>
    </Form>
  );
};

UnitDeployForm = Form.create()(UnitDeployForm);

export default UnitDeployForm;
